<template>
  <div class="buildings-view">
    <!-- 建筑概览 -->
    <div class="buildings-overview">
      <div class="overview-header">
        <h2>建筑管理</h2>
        <div class="overview-actions">
          <button class="action-btn" @click="toggleBuildMode">
            <span class="btn-icon">🏗️</span>
            {{ buildMode ? '退出建造' : '建造模式' }}
          </button>
          <button class="action-btn" @click="openPlanner">
            <span class="btn-icon">📋</span>
            建造规划
          </button>
        </div>
      </div>
      
      <!-- 建筑统计 -->
      <div class="building-stats">
        <StatCard
          v-for="stat in buildingStats"
          :key="stat.id"
          :title="stat.title"
          :value="stat.value"
          :icon="stat.icon"
          :trend="stat.trend"
          :color="stat.color"
        />
      </div>
    </div>

    <!-- 建筑分类 -->
    <div class="building-categories">
      <div class="category-tabs">
        <button
          v-for="category in categories"
          :key="category.id"
          class="category-tab"
          :class="{ active: selectedCategory === category.id }"
          @click="selectedCategory = category.id"
        >
          <span class="tab-icon">{{ category.icon }}</span>
          <span class="tab-name">{{ category.name }}</span>
          <span class="tab-count">{{ category.count }}</span>
        </button>
      </div>
    </div>

    <!-- 建筑列表 -->
    <div class="buildings-content">
      <!-- 左侧：可建造建筑 -->
      <div class="available-buildings">
        <div class="section-header">
          <h3>可建造建筑</h3>
          <div class="building-filters">
            <select v-model="sortBy" class="sort-select">
              <option value="name">按名称排序</option>
              <option value="cost">按成本排序</option>
              <option value="efficiency">按效率排序</option>
            </select>
            <button 
              class="filter-btn"
              :class="{ active: showOnlyAffordable }"
              @click="showOnlyAffordable = !showOnlyAffordable"
            >
              仅显示可建造
            </button>
          </div>
        </div>
        
        <div class="building-grid">
          <BuildingCard
            v-for="building in filteredAvailableBuildings"
            :key="building.id"
            :building="building"
            :can-build="canBuild(building)"
            @build="buildBuilding"
            @info="showBuildingInfo"
          />
        </div>
      </div>

      <!-- 右侧：已建造建筑 -->
      <div class="constructed-buildings">
        <div class="section-header">
          <h3>已建造建筑</h3>
          <div class="building-controls">
            <button 
              class="control-btn"
              @click="toggleAllBuildings"
            >
              {{ allBuildingsActive ? '全部关闭' : '全部开启' }}
            </button>
            <button 
              class="control-btn"
              @click="optimizeProduction"
            >
              优化生产
            </button>
          </div>
        </div>
        
        <div class="constructed-list">
          <div 
            v-for="building in constructedBuildings" 
            :key="building.id"
            class="constructed-item"
            :class="{ inactive: !building.active }"
          >
            <div class="building-info">
              <div class="building-icon">{{ getBuildingIcon(building.templateId) }}</div>
              <div class="building-details">
                <div class="building-name">{{ getBuildingName(building.templateId) }}</div>
                <div class="building-level">等级 {{ building.level }}</div>
                <div class="building-effects">
                  <span 
                    v-for="effect in getBuildingEffects(building)" 
                    :key="effect.type"
                    class="effect-tag"
                  >
                    {{ effect.description }}
                  </span>
                </div>
              </div>
            </div>
            
            <div class="building-status">
              <div class="status-indicator" :class="getBuildingStatusClass(building)">
                {{ getBuildingStatus(building) }}
              </div>
              <div class="efficiency-bar">
                <div class="efficiency-label">效率: {{ building.efficiency }}%</div>
                <div class="progress-bar">
                  <div 
                    class="progress-fill" 
                    :style="{ width: `${building.efficiency}%` }"
                  ></div>
                </div>
              </div>
            </div>
            
            <div class="building-actions">
              <button 
                class="action-btn small"
                @click="toggleBuilding(building.id)"
                :title="building.active ? '关闭建筑' : '开启建筑'"
              >
                {{ building.active ? '⏸️' : '▶️' }}
              </button>
              <button 
                class="action-btn small"
                @click="upgradeBuilding(building.id)"
                :disabled="!canUpgrade(building)"
                title="升级建筑"
              >
                ⬆️
              </button>
              <button 
                class="action-btn small danger"
                @click="demolishBuilding(building.id)"
                title="拆除建筑"
              >
                🗑️
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 建造队列 -->
    <div class="build-queue" v-if="buildQueue.length > 0">
      <div class="section-header">
        <h3>建造队列</h3>
        <button class="action-btn secondary" @click="clearQueue">
          清空队列
        </button>
      </div>
      
      <div class="queue-list">
        <div 
          v-for="(item, index) in buildQueue" 
          :key="index"
          class="queue-item"
        >
          <div class="queue-info">
            <div class="queue-icon">{{ getBuildingIcon(item.templateId) }}</div>
            <div class="queue-details">
              <div class="queue-name">{{ getBuildingName(item.templateId) }}</div>
              <div class="queue-progress">
                <div class="progress-bar">
                  <div 
                    class="progress-fill" 
                    :style="{ width: `${item.progress}%` }"
                  ></div>
                </div>
                <span class="progress-text">{{ Math.round(item.progress) }}%</span>
              </div>
            </div>
          </div>
          
          <div class="queue-time">
            剩余时间: {{ formatTime(item.remainingTime) }}
          </div>
          
          <div class="queue-actions">
            <button 
              class="action-btn small"
              @click="moveQueueItem(index, -1)"
              :disabled="index === 0"
            >
              ⬆️
            </button>
            <button 
              class="action-btn small"
              @click="moveQueueItem(index, 1)"
              :disabled="index === buildQueue.length - 1"
            >
              ⬇️
            </button>
            <button 
              class="action-btn small danger"
              @click="cancelBuild(index)"
            >
              ❌
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 建筑信息模态框 -->
    <BuildingInfoModal
      v-if="showInfoModal"
      :building="selectedBuilding"
      @close="closeInfoModal"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { useBuildingsStore, useResourcesStore } from '@/stores'
import StatCard from '@/components/ui/StatCard.vue'
import BuildingCard from '@/components/ui/BuildingCard.vue'
import BuildingInfoModal from '@/components/ui/BuildingInfoModal.vue'

const buildingsStore = useBuildingsStore()
const resourcesStore = useResourcesStore()

// 响应式数据
const selectedCategory = ref('all')
const buildMode = ref(false)
const sortBy = ref('name')
const showOnlyAffordable = ref(false)
const showInfoModal = ref(false)
const selectedBuilding = ref(null)

// 计算属性
const categories = computed(() => [
  { 
    id: 'all', 
    name: '全部', 
    icon: '🏢', 
    count: buildingsStore.buildings.length 
  },
  { 
    id: 'infrastructure', 
    name: '基础设施', 
    icon: '🏗️', 
    count: buildingsStore.getBuildingsByCategory('infrastructure').length 
  },
  { 
    id: 'industrial', 
    name: '工业建筑', 
    icon: '🏭', 
    count: buildingsStore.getBuildingsByCategory('industrial').length 
  },
  { 
    id: 'research', 
    name: '研究设施', 
    icon: '🔬', 
    count: buildingsStore.getBuildingsByCategory('research').length 
  },
  { 
    id: 'military', 
    name: '军事建筑', 
    icon: '⚔️', 
    count: buildingsStore.getBuildingsByCategory('military').length 
  }
])

const buildingStats = computed(() => [
  {
    id: 'total',
    title: '总建筑数',
    value: buildingsStore.buildings.length,
    icon: '🏢',
    trend: '+2',
    color: 'blue'
  },
  {
    id: 'active',
    title: '运行中',
    value: buildingsStore.buildings.filter(b => b.active).length,
    icon: '⚡',
    trend: '100%',
    color: 'green'
  },
  {
    id: 'efficiency',
    title: '平均效率',
    value: Math.round(buildingsStore.averageEfficiency) + '%',
    icon: '📊',
    trend: '+5%',
    color: 'purple'
  },
  {
    id: 'queue',
    title: '建造队列',
    value: buildingsStore.buildQueue.length,
    icon: '🔨',
    trend: buildingsStore.buildQueue.length > 0 ? '进行中' : '空闲',
    color: 'orange'
  }
])

const availableBuildings = computed(() => {
  return Object.values(buildingsStore.buildingTemplates)
})

const filteredAvailableBuildings = computed(() => {
  let buildings = availableBuildings.value

  // 按分类过滤
  if (selectedCategory.value !== 'all') {
    buildings = buildings.filter(b => b.category === selectedCategory.value)
  }

  // 仅显示可建造的
  if (showOnlyAffordable.value) {
    buildings = buildings.filter(b => canBuild(b))
  }

  // 排序
  buildings.sort((a, b) => {
    switch (sortBy.value) {
      case 'cost':
        return (a.cost?.credits || 0) - (b.cost?.credits || 0)
      case 'efficiency':
        return (b.effects?.length || 0) - (a.effects?.length || 0)
      default:
        return a.name.localeCompare(b.name)
    }
  })

  return buildings
})

const constructedBuildings = computed(() => {
  let buildings = buildingsStore.buildings

  if (selectedCategory.value !== 'all') {
    buildings = buildings.filter(b => {
      const template = buildingsStore.buildingTemplates[b.templateId]
      return template?.category === selectedCategory.value
    })
  }

  return buildings
})

const buildQueue = computed(() => {
  return buildingsStore.buildQueue
})

const allBuildingsActive = computed(() => {
  return constructedBuildings.value.every(b => b.active)
})

// 方法
function getBuildingName(templateId: string): string {
  return buildingsStore.buildingTemplates[templateId]?.name || '未知建筑'
}

function getBuildingIcon(templateId: string): string {
  const icons: Record<string, string> = {
    power_plant: '⚡',
    metal_mine: '⛏️',
    crystal_mine: '💎',
    research_lab: '🔬',
    shipyard: '🚀',
    defense_turret: '🔫'
  }
  return icons[templateId] || '🏢'
}

function getBuildingEffects(building: any) {
  const template = buildingsStore.buildingTemplates[building.templateId]
  if (!template?.effects) return []

  return template.effects.map(effect => ({
    type: effect.type,
    description: `${effect.type}: +${effect.value * building.level}`
  }))
}

function getBuildingStatus(building: any): string {
  if (!building.active) return '已关闭'
  if (building.efficiency < 50) return '效率低'
  if (building.efficiency < 80) return '正常'
  return '高效运行'
}

function getBuildingStatusClass(building: any): string {
  if (!building.active) return 'inactive'
  if (building.efficiency < 50) return 'low'
  if (building.efficiency < 80) return 'normal'
  return 'high'
}

function canBuild(building: any): boolean {
  if (!building.cost) return true
  
  return Object.entries(building.cost).every(([resource, amount]) => {
    return resourcesStore.resources[resource] >= (amount as number)
  })
}

function canUpgrade(building: any): boolean {
  // 简化的升级条件检查
  return building.level < 10 && resourcesStore.resources.credits >= 1000
}

function formatTime(seconds: number): string {
  if (seconds < 60) return `${Math.floor(seconds)}秒`
  if (seconds < 3600) return `${Math.floor(seconds / 60)}分钟`
  if (seconds < 86400) return `${Math.floor(seconds / 3600)}小时`
  return `${Math.floor(seconds / 86400)}天`
}

// 事件处理
function toggleBuildMode() {
  buildMode.value = !buildMode.value
}

function openPlanner() {
  console.log('打开建造规划器')
}

function buildBuilding(building: any) {
  if (canBuild(building)) {
    buildingsStore.buildBuilding(building.id, 'planet-1') // 假设在第一个星球建造
  }
}

function showBuildingInfo(building: any) {
  selectedBuilding.value = building
  showInfoModal.value = true
}

function closeInfoModal() {
  showInfoModal.value = false
  selectedBuilding.value = null
}

function toggleBuilding(buildingId: string) {
  buildingsStore.toggleBuilding(buildingId)
}

function upgradeBuilding(buildingId: string) {
  if (resourcesStore.resources.credits >= 1000) {
    buildingsStore.upgradeBuilding(buildingId)
    resourcesStore.removeResource('credits', 1000)
  }
}

function demolishBuilding(buildingId: string) {
  if (confirm('确定要拆除这个建筑吗？')) {
    buildingsStore.demolishBuilding(buildingId)
  }
}

function toggleAllBuildings() {
  const targetState = !allBuildingsActive.value
  constructedBuildings.value.forEach(building => {
    if (building.active !== targetState) {
      buildingsStore.toggleBuilding(building.id)
    }
  })
}

function optimizeProduction() {
  // 优化生产逻辑
  console.log('优化生产配置')
}

function clearQueue() {
  if (confirm('确定要清空建造队列吗？')) {
    buildingsStore.clearBuildQueue()
  }
}

function moveQueueItem(index: number, direction: number) {
  const newIndex = index + direction
  if (newIndex >= 0 && newIndex < buildQueue.value.length) {
    // 移动队列项目
    console.log(`移动队列项目从 ${index} 到 ${newIndex}`)
  }
}

function cancelBuild(index: number) {
  if (confirm('确定要取消这个建造项目吗？')) {
    buildingsStore.cancelBuild(index)
  }
}
</script>

<style scoped>
.buildings-view {
  padding: 1rem;
  height: 100%;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.overview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.overview-header h2 {
  margin: 0;
  color: #ffffff;
  font-size: 1.5rem;
}

.overview-actions {
  display: flex;
  gap: 0.5rem;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  background: #00d4ff;
  color: #000000;
  border: none;
  border-radius: 6px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.action-btn:hover {
  background: #0099cc;
  transform: translateY(-1px);
}

.action-btn.secondary {
  background: rgba(255, 255, 255, 0.1);
  color: #ffffff;
}

.action-btn.secondary:hover {
  background: rgba(255, 255, 255, 0.2);
}

.action-btn.small {
  padding: 0.25rem 0.5rem;
  font-size: 0.875rem;
}

.action-btn.danger {
  background: rgba(255, 68, 68, 0.2);
  color: #ff4444;
}

.action-btn.danger:hover {
  background: #ff4444;
  color: #ffffff;
}

.btn-icon {
  font-size: 1rem;
}

.building-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem;
  margin-bottom: 1rem;
}

.category-tabs {
  display: flex;
  gap: 0.5rem;
  margin-bottom: 1rem;
  overflow-x: auto;
}

.category-tab {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.75rem 1rem;
  background: rgba(255, 255, 255, 0.1);
  color: #cccccc;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  white-space: nowrap;
}

.category-tab:hover {
  background: rgba(255, 255, 255, 0.2);
}

.category-tab.active {
  background: #00d4ff;
  color: #000000;
}

.tab-icon {
  font-size: 1.2rem;
}

.tab-name {
  font-weight: 500;
}

.tab-count {
  background: rgba(0, 0, 0, 0.2);
  padding: 0.125rem 0.375rem;
  border-radius: 4px;
  font-size: 0.75rem;
  font-weight: bold;
}

.buildings-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1.5rem;
  flex: 1;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.section-header h3 {
  margin: 0;
  color: #00d4ff;
  font-size: 1.2rem;
}

.building-filters {
  display: flex;
  gap: 0.5rem;
  align-items: center;
}

.sort-select {
  padding: 0.375rem 0.75rem;
  background: rgba(0, 0, 0, 0.4);
  color: #ffffff;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 4px;
  font-size: 0.875rem;
}

.filter-btn {
  padding: 0.375rem 0.75rem;
  background: rgba(255, 255, 255, 0.1);
  color: #cccccc;
  border: none;
  border-radius: 4px;
  font-size: 0.875rem;
  cursor: pointer;
  transition: all 0.2s ease;
}

.filter-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.filter-btn.active {
  background: #00d4ff;
  color: #000000;
}

.building-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 1rem;
  max-height: 600px;
  overflow-y: auto;
}

.constructed-list {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
  max-height: 600px;
  overflow-y: auto;
}

.constructed-item {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem;
  background: rgba(0, 0, 0, 0.4);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  transition: all 0.2s ease;
}

.constructed-item:hover {
  border-color: #00d4ff;
}

.constructed-item.inactive {
  opacity: 0.6;
}

.building-info {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  flex: 1;
}

.building-icon {
  font-size: 2rem;
  min-width: 40px;
}

.building-details {
  flex: 1;
}

.building-name {
  font-weight: 600;
  color: #ffffff;
  margin-bottom: 0.25rem;
}

.building-level {
  font-size: 0.875rem;
  color: #00d4ff;
  margin-bottom: 0.25rem;
}

.building-effects {
  display: flex;
  gap: 0.25rem;
  flex-wrap: wrap;
}

.effect-tag {
  font-size: 0.75rem;
  color: #888888;
  background: rgba(255, 255, 255, 0.05);
  padding: 0.125rem 0.375rem;
  border-radius: 3px;
}

.building-status {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.5rem;
  min-width: 120px;
}

.status-indicator {
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.75rem;
  font-weight: 500;
}

.status-indicator.inactive {
  background: rgba(128, 128, 128, 0.2);
  color: #888888;
}

.status-indicator.low {
  background: rgba(255, 68, 68, 0.2);
  color: #ff4444;
}

.status-indicator.normal {
  background: rgba(245, 158, 11, 0.2);
  color: #f59e0b;
}

.status-indicator.high {
  background: rgba(0, 255, 136, 0.2);
  color: #00ff88;
}

.efficiency-bar {
  width: 100%;
}

.efficiency-label {
  font-size: 0.75rem;
  color: #cccccc;
  margin-bottom: 0.25rem;
  text-align: center;
}

.progress-bar {
  height: 6px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 3px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #00d4ff, #0099cc);
  transition: width 0.3s ease;
}

.building-actions {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.build-queue {
  background: rgba(0, 0, 0, 0.4);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  padding: 1rem;
}

.queue-list {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.queue-item {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 0.75rem;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 6px;
}

.queue-info {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  flex: 1;
}

.queue-icon {
  font-size: 1.5rem;
}

.queue-details {
  flex: 1;
}

.queue-name {
  font-weight: 500;
  color: #ffffff;
  margin-bottom: 0.25rem;
}

.queue-progress {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.progress-text {
  font-size: 0.75rem;
  color: #cccccc;
  min-width: 35px;
}

.queue-time {
  font-size: 0.875rem;
  color: #888888;
  min-width: 100px;
}

.queue-actions {
  display: flex;
  gap: 0.25rem;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .buildings-content {
    grid-template-columns: 1fr;
  }
  
  .building-stats {
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  }
}

@media (max-width: 768px) {
  .buildings-view {
    padding: 0.5rem;
    gap: 1rem;
  }
  
  .overview-header {
    flex-direction: column;
    align-items: stretch;
    gap: 0.5rem;
  }
  
  .overview-actions {
    justify-content: center;
  }
  
  .category-tabs {
    justify-content: center;
  }
  
  .section-header {
    flex-direction: column;
    align-items: stretch;
    gap: 0.5rem;
  }
  
  .building-filters {
    justify-content: center;
  }
  
  .building-grid {
    grid-template-columns: 1fr;
  }
  
  .constructed-item {
    flex-direction: column;
    align-items: stretch;
    gap: 0.75rem;
  }
  
  .building-info {
    justify-content: center;
  }
  
  .building-actions {
    flex-direction: row;
    justify-content: center;
  }
}
</style>